import 'package:http/http.dart' as http;
import '../models/song.dart';
import 'package:crypto/crypto.dart';
import 'dart:convert';

class SearchService {
  static const String baseUrl = 'http://www.qeecc.com';

  static final Map<String, String> _browserHeaders = {
    'User-Agent':
        'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
    'Accept':
        'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
    'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
    'Connection': 'keep-alive',
    'Cache-Control': 'max-age=0',
  };

  static Future<List<Song>> searchSongs(String keyword) async {
    try {
      final searchUrl =
          Uri.parse('$baseUrl/so/${Uri.encodeComponent(keyword)}.html');
      final response = await http.get(
        searchUrl,
        headers: {
          ..._browserHeaders,
          'Referer': baseUrl,
        },
      );

      if (response.statusCode != 200) {
        throw Exception('搜索请求失败: ${response.statusCode}');
      }

      // 修改正则表达式以正确匹配歌手和歌名
      final songRegex = RegExp(
          r'<a href="/song/([a-zA-Z0-9]+)\.html"[^>]*>([^《]+)《([^》]+)》\[Mp3\]</a>');
      final matches = songRegex.allMatches(response.body);

      List<Song> songs = [];
      for (var match in matches) {
        final songId = match.group(1)!;
        final artist = match.group(2)!.trim();
        final title = match.group(3)!.trim();

        print("songId:$songId, artist: $artist, title: $title");

        // 生成唯一的songId
        final uniqueId =
            md5.convert(utf8.encode('${artist}_${title}')).toString();

        songs.add(Song(
          songId: uniqueId,
          title: title,
          artist: artist,
          downloadUrl: '',
          isDownloaded: false,
        ));
      }

      return songs;
    } catch (e) {
      print('搜索失败: $e');
      return [];
    }
  }
}
